package com.isoftstone.studentregistration.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.isoftstone.studentregistration.pojo.Users;
import com.isoftstone.studentregistration.service.UserService;
import com.isoftstone.studentregistration.util.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

//用户控制器类
@RestController
@RequestMapping("/api")
@Slf4j
public class UserController {
    //注入Userservice实例
    @Autowired
    private UserService userService;



    @PostMapping("/user")
    public Result<?> insertUser(@RequestBody Users user) {

        return userService.insertUser(user);
    }

    //修改用户信息
    @PutMapping("/user")
    public Result<?> updateUser(@RequestBody Users user) {
        return userService.updateUser(user);
    }

    //删除用户
    @DeleteMapping("/user/{id}")
    public Result<?> deleteUser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }
//分页查询所有用户
    @GetMapping("/user")
    public Result<?> queryAllUsers(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize) {
        Page page = userService.queryAllUsers(currentPage, pageSize);
        PageInfo<Object> pageInfo = new PageInfo<>(page);
        return Result.success(pageInfo);
    }
    //生成验证码
    private LineCaptcha lineCaptcha;
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse  response) {
        lineCaptcha= CaptchaUtil.createLineCaptcha(125,45);
        lineCaptcha.setBackground(new Color(181,238,218));

        try{
            ServletOutputStream os =response.getOutputStream();
            lineCaptcha.write(os);
            os.flush();
            os.close();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String,String> user){
       //获取用户输入的验证码
        String code = user.get("code");
        if(!lineCaptcha.verify(code)){
            return Result.fail("验证码错误");
        }
        return userService.login(user.get("phone"),user.get("password"));
    }

//文件导出
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        userService.exportExcel(response);
    }


    /**
     * 文件导入模板
     * @param
     * @return
     * @throws IOException
     */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        userService.importTemplate(response);
    }

    @PostMapping("/import")
    public Result<?> importExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要导入的Excel文件");
        }

        InputStream is = null;
        ExcelReader excelReader = null;
        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMsg = new StringBuilder();

        try {
            // 获取输入流
            is = file.getInputStream();
            // 读取Excel
            excelReader = ExcelUtil.getReader(is);
            List<Users> usersList = excelReader.readAll(Users.class);

            if (usersList == null || usersList.isEmpty()) {
                return Result.fail("Excel文件中没有数据");
            }

            for (Users user : usersList) {
                try {
                    // 验证用户数据
                    if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                        failCount++;
                        errorMsg.append("用户名不能为空; ");
                        continue;
                    }

                    Result<?> result = userService.insertUser(user);
                    if (result != null && "操作成功".equals(result.getMessage())) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMsg.append("用户 <b>").append(user.getUsername()).append("</b> 插入失败; ");
                    }
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("用户 <b>").append(user.getUsername()).append("</b> 插入异常: ")
                            .append(e.getMessage()).append("; ");
                    // 记录详细异常日志
                    log.error("导入用户异常", e);
                }
            }

            // 构建返回结果
            if (failCount > 0) {
                return Result.success("数据导入完成，成功: <b>" + successCount + "</b>条，失败: <b>" + failCount + "</b>条。"
                        + errorMsg.toString());
            } else {
                return Result.success("数据导入成功，共导入" + successCount + "条记录");
            }

        } catch (IOException e) {
            log.error("Excel文件读取失败", e);
            return Result.fail("文件读取失败：" + e.getMessage());
        } finally {
            // 关闭资源
            if (excelReader != null) {
                try {
                    excelReader.close();
                } catch (Exception e) {
                    log.error("ExcelReader关闭失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("输入流关闭失败", e);
                }
            }
        }
    }
    //批量删除
    @DeleteMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestParam List<Integer> ids) {
        return userService.deleteBatch(ids);
    }
//状态更新
    @PutMapping("/users/{id}/status")
    public Result<Integer> updateStatus(@PathVariable Integer id,
                                        @RequestBody Map<String,String> body) {
        String status = body.get("status");
        if (status == null) return Result.fail("status 不能为空");
        return userService.updateStatus(id, status);
    }

    //根据状态或者用户名分页查询
    @GetMapping("/query")
    public Result<PageInfo<Users>> queryUsers(
            @RequestParam(defaultValue = "1") Integer currentPage,  // 前端传递的页码
            @RequestParam(defaultValue = "5") Integer pageSize,     // 前端传递的页大小
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status) {

        // 调用修改后的Service方法（传递currentPage和pageSize）
        PageInfo<Users> pageInfo = userService.queryUsers(status, username, currentPage, pageSize);
        return Result.success(pageInfo);
    }
}



